<template>
  <el-container>
    <el-main>
      <el-row type="flex" class="row-bg" justify="center">
        <el-col :xs="20" :sm="16" :md="10" :lg="8" :xl="6">
          <el-form ref="form" :model="form" label-width="120px" v-loading="loading">
            <el-form-item label="Username">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="Password">
              <el-input show-password v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item v-if="!!errorMessage">
              <error-alert :errorMessage="errorMessage" @ok="errorOk"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" native-type="submit" @click="onSubmit">Log in</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-main>
    <el-footer><a href="https://beian.miit.gov.cn/">粤 ICP 备 2020099176 号</a></el-footer>
  </el-container>
</template>

<style>
html, body, div#app, section {
  height: 100%;
}
footer {
  text-align: center;
}
</style>

<script>
import http from "../util/http.js";

import elementContainer from '../plugins/element/container.js';
import elementLayout from "../plugins/element/layout.js";
import elementForm from "../plugins/element/form.js";
import elementInput from "../plugins/element/input.js";
import elementButton from "../plugins/element/button.js";

import ErrorAlert from "../components/ErrorAlert.vue";

const component = {
  name: "login",
  data () {
    return {
      form: {
        username: "",
        password: "",
      },
      errorMessage: "",
      loading: false
    };
  },
  methods: {
    onSubmit (event) {
      event.stopPropagation();
      event.preventDefault();
      this.loading = true;
      http.post( http.receiveJSON({
        url: "/login",
        data: {
          username: this.form.username,
          password: this.form.password
        }
      }) ).then(response => {
        this.loading = false;
        if (response.data.code === "ok") {
          this.$router.push({
            name: "model_list"
          });
        } else {
          this.errorMessage = response.data.msg;
        }
      }).catch(ex => {
        console.error(ex);
        this.loading = false;
        this.errorMessage = "登录失败";
      });
      return false;
    },
    errorOk () {
      this.errorMessage = "";
    }
  },
  components: {
    ErrorAlert
  }
};

elementContainer(component);
elementLayout(component);
elementForm(component);
elementInput(component);
elementButton(component);

export default component;
</script>
